package com.ruoyi.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.login.entity.LoginVo;
import com.ruoyi.system.service.ISysUserService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/h5/login")
public class LoginControllerH5 {

    @Autowired
    private LoginVo loginVo;

    @GetMapping("/getSessionKey/{code}")
    public String getSessionKey(@PathVariable("code") String code) throws IOException {

        //创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + loginVo.getAppId() +
                "&secret=" + loginVo.getAppSecret() + "&js_code=" + code;

        //创建get请求
        HttpGet httpGet = new HttpGet(url);
        //执行get请求
        HttpResponse response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() == 200) {
            //解析实体
            HttpEntity res = response.getEntity();
            String message = EntityUtils.toString(res, "utf-8");
            JSONObject jsonObject = (JSONObject) JSONObject.parse(message);
            String session_key = jsonObject.getString("session_key");
            return session_key;
        }
        return null;
    }

}
